#!/bin/bash

function u2d_list {
  for file in $1; do
    echo $file | egrep -q "\.(reg|txt|diz|ini|temp|lua|farconfig|lng|hlf)$" && unix2dos $2/$file
  done
}

function bplugin2 {
PLUGIN=$1
BIT=$2
MASKS=$3
FILES=$4

FINAL=Release.${BIT}.vc

ADD=0
if [ "$PLUGIN" == "FTP" ]; then
  ADD=1
elif [ "$PLUGIN" == "MultiArc" ]; then
  ADD=1
fi

mkdir -p ${FINAL}/obj
if [ $ADD -eq 1 ]; then
  eval "mkdir -p ${FINAL}/$6"
fi

wine cmd /c ../../plugin.${BIT}.bat &> ../../logs/${PLUGIN}${BIT}

if [ $ADD -eq 1 ]; then
  mkdir -p ../../outfinalnew${BIT}/Plugins/$PLUGIN
  mkdir -p ../../outfinalnew${BIT}/Plugins/${PLUGIN}/$7

  cp -f changelog ../../outfinalnew${BIT}/Plugins/$PLUGIN/  

  cd $FINAL || return 1
  if [ $MASKS -eq 1 ]; then
    FILES=`ls $FILES 2>/dev/null`
  fi
  cp -f $FILES ../../../outfinalnew${BIT}/Plugins/$PLUGIN/ || return 1
  u2d_list "$FILES" ../../../outfinalnew${BIT}/Plugins/$PLUGIN/
  cd ..

  cd $FINAL/$7 || return 1
  cp -f $5 ../../../../outfinalnew${BIT}/Plugins/${PLUGIN}/$7/ || return 1
  u2d_list "$5" ../../../../outfinalnew${BIT}/Plugins/${PLUGIN}/$7/
  cd ../..
else
  mkdir -p ../../outfinalnew${BIT}/Plugins/$PLUGIN

  cp -f changelog ../../outfinalnew${BIT}/Plugins/$PLUGIN/  

  cd $FINAL || return 1
  if [ $MASKS -eq 1 ]; then
    FILES=`ls $FILES 2>/dev/null`
  fi
  cp -f $FILES ../../../outfinalnew${BIT}/Plugins/$PLUGIN/ || return 1
  u2d_list "$FILES" ../../../outfinalnew${BIT}/Plugins/$PLUGIN/
  cd ..
fi
}

function bplugin {
PLUGIN=$1
PLDIR=$2

pushd $PLUGIN || return 1

unix2dos changelog

( \
	bplugin2 "$PLDIR" 32 1 "$3" && \
	bplugin2 "$PLDIR" 64 1 "$3" && \
	bplugin2 "$PLDIR" ARM64 1 "$3" \
) || return 1

popd
}
